package com.yeeverse.sdk.api;

import com.yeeverse.sdk.exception.SdkException;
import com.yeeverse.sdk.util.JsonUtils;
import com.yeeverse.sdk.util.RSAUtils;
import com.yeeverse.sdk.vo.api.BaseResponse;
import com.yeeverse.sdk.vo.api.subMerchantApply.ApiUploadRequestDTO;
import org.apache.commons.codec.digest.DigestUtils;

import java.io.*;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.WritableByteChannel;

public class PayUploadApi {


    private static void copFiles(WritableByteChannel target, File file) throws Exception {
        FileInputStream fis = null;
        FileChannel channel = null;
        try {
            fis = new FileInputStream(file);
            channel = fis.getChannel();

            long imageFileSize = channel.size();
            double msize = new BigDecimal((float) imageFileSize / (1024 * 1024)).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            if (msize > 10) {
                throw new SdkException("文件大小不能超过10M");
            }

            channel.transferTo(0, channel.size(), target);

        } finally {
            try {
                if (channel != null) {
                    channel.close();
                }
                if (fis != null) {
                    fis.close();
                }
            } catch (IOException e) {
            }
        }


    }

    public static String sendUploadFile(String urlStr, ApiUploadRequestDTO apiUploadRequestDTO) throws Exception {
        DataOutputStream ds = null;
        BufferedReader br;
        FileInputStream fileInputStream = null;

        try {
            String end = "\r\n";
            String twoHyphens = "--";
            String boundary = "*****";

            URL url = new URL(urlStr);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            /* 允许Input、Output，不使用Cache */
            con.setDoInput(true);
            con.setDoOutput(true);
            con.setUseCaches(false);
            /* 设置传送的method=POST */
            con.setRequestMethod("POST");

            //文件签名
            fileInputStream = new FileInputStream(apiUploadRequestDTO.getFile());
            String sha256 = DigestUtils.sha256Hex(fileInputStream);


            //aesKey加密存储
            String rsaAesKey = RSAUtils.encryptByPublicKey(SdkContext.getCurrentSdk().getAesKey(), SdkContext.getCurrentSdk().getPublictKey());

            con.setRequestProperty("APPID", SdkContext.getCurrentSdk().getAppId());
            con.setRequestProperty("sign", sha256);
            con.setRequestProperty("Connection", "Keep-Alive");
            con.setRequestProperty("Charset", "UTF-8");
            con.setRequestProperty("fileName", apiUploadRequestDTO.getFileName());
            con.setRequestProperty("parentMerchantNo", apiUploadRequestDTO.getParentMerchantNo());
            con.setRequestProperty("AESKEY", rsaAesKey);

            con.setRequestProperty("Content-Type",
                    "multipart/form-data;boundary=" + boundary);
            /* 设置DataOutputStream */
            ds = new DataOutputStream(con.getOutputStream());
            ds.writeBytes(twoHyphens + boundary + end);
            ds.writeBytes("Content-Disposition: form-data; "
                    + "name=\"file1\";filename=\"" + apiUploadRequestDTO.getFileName() + "\"" + end);
            ds.writeBytes(end);

            // 进行零拷贝，提升文件性能
            WritableByteChannel writableByteChannel = Channels.newChannel(ds);

            copFiles(writableByteChannel, apiUploadRequestDTO.getFile());

            ds.writeBytes(end);
            ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
            /* close streams */
            ds.flush();

            StringBuilder sb = new StringBuilder();
            int HttpResult = con.getResponseCode();
            if (HttpResult == HttpURLConnection.HTTP_OK) {
                br = new BufferedReader(new InputStreamReader(con.getInputStream(), "utf-8"));
                String line;
                while ((line = br.readLine()) != null) {
                    sb.append(line + "\n");
                }
                return sb.toString();

            } else {
                BaseResponse baseResponse = new BaseResponse();
                baseResponse.setCode("GW999999");
                baseResponse.setMessage("请求api异常");
                return JsonUtils.toJsonString(baseResponse);
            }

        } catch (SdkException e) {
            BaseResponse baseResponse = new BaseResponse();
            baseResponse.setCode("GW999999");
            baseResponse.setMessage(e.getMessage());
            return JsonUtils.toJsonString(baseResponse);

        } finally {
            try {
                if (fileInputStream != null) {
                    fileInputStream.close();
                }
                if (ds != null) {
                    ds.close();
                }
            } catch (IOException e) {
            }

        }

    }


}
